<?php
namespace Home\Controller;
class SnatchController extends HomeController {

	public function index(){
		$keyword = I('keyword');
		$order_type = I('order_type','view_num');
		$status = I('status',-1);
		$order_sort = '';
		if ($order_type == 'remaining') {
			$order_sort = "(total_num - num) asc";
		}else{
			$order_sort = $order_type . " desc";
		}
		$map = array(
			"title"	=>	array('like',"%".$keyword."%")
		);
		if ($status >= 0) {
			$map['status'] = $status;
			if ($status == 0) {
				$map['lottery_uid']	= ['gt',0];
			}
		}
		$list = $this->lists('snatch',$map,$order_sort);
		$this->assign('order_type',$order_type);
		$this->assign('keyword',$keyword);
		$this->assign('status',$status);
		$this->assign('list',$list);
		$this->display();
	}
	/**
	 * 添加人品大爆发
	 */
	public function add(){
		if (IS_POST) {
			if (!defined("UID") || UID == 0) {
				$this->error("请先登录",U('login/index'));
				exit();
			}
			$data = I('post.');
			if (empty($_FILES['pic']['name'])) {
				$this->error("请上传图片");
			}
			if (isset($_FILES['pic']['name'])) {
		        $Picture = D('Picture');
		        $pic_driver = C('PICTURE_UPLOAD_DRIVER');
		        $info = $Picture->upload(
		            $_FILES,
		            C('PICTURE_UPLOAD'),
		            C('PICTURE_UPLOAD_DRIVER'),
		            C("UPLOAD_{$pic_driver}_CONFIG")
		        );
		        if ($info) {
		        	$data['pic'] = $info['pic']['id'];
		        }else{
		        	$this->error("上传图片失败！");
		        }
			}
			if (isset($_FILES['video']['name']) && !empty($_FILES['video']['name'])) {
		        $Movie = D('Movie');
		        $movie_driver = C('DOWNLOAD_UPLOAD_DRIVER');
		        $info = $Movie->upload(
		            $_FILES,
		            C('MOVIE_UPLOAD'),
		            C('DOWNLOAD_UPLOAD_DRIVER'),
		            C("UPLOAD_{$movie_driver}_CONFIG")
		        );
		        if ($info) {
		        	$data['video'] = intval($info['video']['id']);
		        }else{
		        	$this->error("上传视频失败！".$Movie->error);
		        }
			}else{
				unset($data['video']);
			}
			$data['start_time'] = strtotime($data['start_time']);
			$data['end_time'] = strtotime($data['end_time']);
			$data['add_time'] = time();
			if ($data['start_time'] >= $data['end_time']) {
				$this->error("活动开始时间有误");
			}
			if ($data['start_time'] <= NOW_TIME && $data['end_time'] > NOW_TIME) {
				$data['status'] = 1;
			}elseif ($data['end_time'] < NOW_TIME) {
				$data['status'] = 2;
			}
			$data['uid']	 = UID;
			$result = M('snatch')->add($data);
			if ($result !== false) {
				$this->success("添加成功",U('detail',['id'=>$result]));
			}else{
				$this->error("添加失败");
			}
			exit();
		}
		$goods_id = I('goods_id',0);
		$prize = 'coin';
		if ($goods_id > 0) {
			$goods_info = M('product')->field('id,title,price')->where('id='.$goods_id)->find();
			if (!empty($goods_info)) {
				$prize = "cash";
				$this->assign('goods_info',$goods_info);
			}
		}
		$this->assign('prize',$prize);
		$this->display();
	}
	/**
	 * 人品大爆发详情
	 * @return [type] [description]
	 */
	public function detail(){
		$id = I('id');
		$info = M('snatch')->find($id);
		if ($info['video'] > 0) {
			$info['video_info'] = get_movie($info['video']);
			$info['video_path'] = '/Uploads/Movie/' . get_movie($info['video'], 'savepath') . get_movie($info['video'], 'savename');
		}
		$map = array(
			'snatch_id'	=>	$id,
			'status'	=>	array('gt',0)
		);
		$join_list = M('user_code')->where($map)->select();
		$join_code_info = array();
		foreach ($join_list as $key => $value) {
			if (is_login()) {
				if ($value['uid'] == UID) {
					$join_code_info = $value;
				}
			}
		}
		$this->assign("uid",is_login()?UID:-1);
		$this->assign('join_list',$join_list);
		$this->assign('join_code_info',$join_code_info);
		$this->assign('info',$info);
		$this->display();
	}
	public function rule(){
		$this->assign("snatch_rule",str_replace("\n","<br />",C('SNATCH_RULE')));
		$this->display();
	}
	/**
	 * 获取幸运数字
	 * @return [type] [description]
	 */
	public function getCode(){
		$id = intval(I('id'));
		$this->assign("snatch_id",$id);
		$this->display();
	}
	/**
	 * 获取幸运码
	 * @return [type] [description]
	 */
	public function ajaxCheckCode(){
		if(!is_login()){
			$this->error('请先登录', U('login/index'));
		}
		$snatch_id = intval(I('snatch_id'));
		// 判断活动状态
		$snatch_info = M("snatch")->find($snatch_id);
		if ($snatch_info['status'] != 1) {
			$this->error("活动信息错误！");
		}
		// 判断是否已参加支付幸运码
		$map = array(
			'uid'	=>	UID,
			'snatch_id'	=>	$snatch_id,
			'status'	=>	array('gt',0)
		);
		$check_code = M('user_code')->where($map)->count();
		if ($check_code > 0) {
			$this->error("您已支付幸运号，请等待开奖",U('index/index'));
		}
		// 生成幸运码
		$code = $this->buildCode($snatch_id);
		// 幸运码入库
		$data = array(
			'uid'	=>	UID,
			'snatch_id'	=>	$snatch_id,
			'code'		=>	$code,
			'money'	=>	$snatch_info['money'],
			'status'	=>	0,
			'pay_sn'	=>	build_no(),
			'add_time'	=>	time()
		);
		$result = M('user_code')->add($data);
		if ($result !== false) {
			exit(json_encode(array('status'=>1,'code'=>$code,'user_code_id'=>$result)));
		}else{
			$this->error("获取幸运码失败,请重试");
		}
	}
	public function deleteCancelCode(){
        !is_login() && $this->error('请先登录', U('login/index'));
		$id = intval(I('id'));
		$map = array(
			'uid'	=>	UID,
			'id'	=>	$id,
			'status'	=>	0
		);
		$result = M('user_code')->where($map)->delete();
		if ($result !== false) {
			$this->success("取消删除成功");
		}else{
			$this->error("删除失败");
		}
	}
	/**
	 * 开奖
	 * @return [type] [description]
	 */
	public function lottery(){
        !is_login() && $this->error("请登录后操作",U('login/index'));
		$snatch_id = I("snatch_id");
		$snatch_info = M('snatch')->where(array('id'=>$snatch_id,'status'=>1))->find();
		if (empty($snatch_info)) {
			$this->error("活动信息错误");
		}
		if ($snatch_info['uid'] != UID) {
			$this->error("非发起人，无权开奖");
		}
		if ($snatch_info['num'] <= 0) {
			$this->error("暂无人参与活动，无法开奖");
		}
		$result = snatch_lottery($snatch_id);
		if ($result !== false) {
			$lottery_code_info = M('snatch')->field('lottery_uid,lottery_code,lottery_time')->find($snatch_id);
			$lottery_code_info['nickname'] = get_nickname($lottery_code_info['lottery_uid']);
			exit(json_encode(array('status'=>1,'lottery_info'=>$lottery_code_info)));
		}else{
			$this->error("开奖失败");
		}
	}
	/**
	 * 生成随机数
	 * @param  [type] $snatch_id [description]
	 * @return [type]            [description]
	 */
	private function buildCode($snatch_id){
		$code = str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_RIGHT);
		$check = M('user_code')->where(array('snatch_id'=>$snatch_id,'code'=>$code,'status'=>1))->count();
		if ($check > 0) {
			return $this->buildCode($snatch_id);
		}else{
			return $code;
		}
	}
}